package com.aacar.op.service.img;

import com.aacar.op.dao.img.ImgDao;
import com.aacar.op.entity.img.Img;
import com.aacar.op.utils.DefineAppConfigLoader;
import com.aacar.op.utils.ImageTool;
import com.aacar.op.utils.web.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ImgServiceImpl implements IImgService {
    private static Logger logger = LoggerFactory.getLogger(ImgServiceImpl.class);
    @Autowired
    private ImgDao imgDao;


    @Override
    public Img uploadFile(Img img, MultipartFile multipartFile) throws Exception {
        ImageTool imageTool = ImageTool.getInstance();
        String path = DefineAppConfigLoader.getProperty("aacar.upload.root.path");
        String type = img.getType();
        String oriImgName = imageTool.getGenImageName(img.getType(), multipartFile.getOriginalFilename());
        
        //根据类型生成 图片目录
        if("1".equals(type)){ //洗车工头像
			path += DefineAppConfigLoader.getProperty("aacar.static.washer.header.path");
		}

        String imgPath = path;
        
        String oriPath = imgPath + oriImgName;
        img.setName(oriImgName);
        logger.debug("保存图片原图 : {}", oriPath);
        imageTool.saveImg(multipartFile, oriPath);
        return img;
    }

    @Override
    public Img get(Long id) {
        return imgDao.findOne(id);
    }

    @Override
    public int delete(Long id) {
        return imgDao.delete(id);
    }

    @Override
    public int saveOrUpdate(Img entity) {
        int ret;
        entity.auditObject();
        if (entity.isNew()) {
            ret = imgDao.insert(entity);
        } else {
            ret = imgDao.update(entity);
        }
        return ret;
    }

    @Override
    public PageInfo<Img> getPage(Map<String, Object> params, Pageable pageable) {
        PageUtils.mergeSort(params, pageable);
        //pageNum(页码)从1开始,spring data common domain从0开始的.
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Img> pageContent = imgDao.findAll(params);
        return new PageInfo(pageContent);
    }


}

